package com.zhfi.dataapply.util;

import com.zhfi.dataapply.service.JobSettingService;
import com.zhfi.dataapply.service.common.JobRangeDateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Component
public class JobUtil {

    @Autowired
    private JobSettingService jobSettingService;

    @Autowired
    private JobRangeDateService jobRangeDateService;

    public void doJobStart(String jobName) {
        log.info("-----{}Job开始-----", jobName);
        jobSettingService.running(jobName);
    }

    public void doJobEnd(String jobName, JobExecution jobExecution) {
        log.info("-----{}Job结束-----", jobName);
        BatchStatus status = jobExecution.getStatus();
        if (BatchStatus.COMPLETED.equals(status)){
            jobSettingService.finished(jobName);
        } else {
            jobSettingService.failed(jobName);
        }
    }

    public void doRangeDateJobEnd(String jobName, JobExecution jobExecution) {
        log.info("-----{}Job结束-----", jobName);
        BatchStatus status = jobExecution.getStatus();
        if (BatchStatus.COMPLETED.equals(status)){
            jobSettingService.finished(jobName);
            changeRangeDate(jobName);
        } else {
            jobSettingService.failed(jobName);
            changeEndDate(jobName);
        }
    }

    public void changeRangeDate(String jobName) {
        Calendar instance = Calendar.getInstance();
        Date startDate = instance.getTime();
        instance.add(Calendar.DATE, 1);
        Date endDate = instance.getTime();
        changeRangeDate(jobName, startDate, endDate);
    }

    public void changeRangeDate(String jobName, Date startDate, Date endDate) {
        jobRangeDateService.updateRangeDate(jobName, startDate, endDate);
    }

    public void changeEndDate(String jobName) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);
        Date endDate = instance.getTime();
        jobRangeDateService.updateEndDate(jobName, endDate);
    }

}
